/**
 * Copyright 2020 jianggujin (www.jianggujin.com).
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jianggujin.dbfly.mybatis.builder.method;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.jianggujin.dbfly.mybatis.constant.JOrderStrategy;
import com.jianggujin.dbfly.util.JStringUtils;

/**
 * 排序部分
 * 
 * @author jianggujin
 *
 */
public class JOrderBySource {

    static JOrderBySource EMPTY = new JOrderBySource("");

    private static final String BLOCK_SPLIT = "(?<=Asc|Desc)(?=\\p{Lu})";
    private static final Pattern DIRECTION_SPLIT = Pattern.compile("(.+?)(Asc|Desc)?$");
    private static final String INVALID_ORDER_SYNTAX = "Invalid order syntax for part %s!";
    private static final Set<String> DIRECTION_KEYWORDS = new HashSet<String>(Arrays.asList("Asc", "Desc"));

    private final List<JOrder> orders;

    protected JOrderBySource(String clause) {

        this.orders = new ArrayList<JOrder>();

        if (!JStringUtils.hasText(clause)) {
            return;
        }

        for (String part : clause.split(BLOCK_SPLIT)) {

            Matcher matcher = DIRECTION_SPLIT.matcher(part);

            if (!matcher.find()) {
                throw new IllegalArgumentException(String.format(INVALID_ORDER_SYNTAX, part));
            }

            String propertyString = matcher.group(1);
            String directionString = matcher.group(2);

            // No property, but only a direction keyword
            if (DIRECTION_KEYWORDS.contains(propertyString) && directionString == null) {
                throw new IllegalArgumentException(String.format(INVALID_ORDER_SYNTAX, part));
            }

            this.orders.add(createOrder(propertyString, JOrderStrategy.fromOptionalString(directionString)));
        }
    }

    /**
     * 创建排序对象
     * 
     * @param propertySource
     * @param direction
     * @return
     */
    private JOrder createOrder(String propertySource, JOrderStrategy direction) {
        if (direction != null) {
            return new JOrder(direction, JStringUtils.firstCharToLowerCase(propertySource));
        } else {
            return JOrder.by(JStringUtils.firstCharToLowerCase(propertySource));
        }
    }

    protected JSort toSort() {
        return JSort.by(this.orders);
    }

    @Override
    public String toString() {
        return JStringUtils.format("Order By {}", JStringUtils.collectionToDelimitedString(orders, ", "));
    }
}
